package com.chen.apipassenger.service;

import com.chen.internalcommon.constant.CommonStatusEnum;
import com.chen.internalcommon.dto.ResponseResult;
import com.chen.internalcommon.dto.TokenResult;
import com.chen.internalcommon.response.TokenResponse;
import com.chen.internalcommon.util.JwtUtils;
import com.chen.internalcommon.util.RedisPrefixUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author chenLiuPing
 **/
@Service
public class TokenService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ResponseResult refreshToken(String refreshTokenSrc) {
        // 解析refreshTokenSrc
        TokenResult tokenResult = JwtUtils.parseToken(refreshTokenSrc);
        if (tokenResult == null) {
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR);
        }
        // 从redis查询refreshTokenSrc 进行校验
        String phone = tokenResult.getPhone();
        String identity = tokenResult.getIdentity();
        String refreshTokenSrcKey = RedisPrefixUtils.generateRefreshTokenKey(phone, identity);
        String refreshTokenRedis = stringRedisTemplate.opsForValue().get(refreshTokenSrcKey);
        if (!StringUtils.hasText(refreshTokenRedis)) {
            // TODO 这里应该是token过期
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR);
        }

        // 返回新的refreshToken 和accessToken
        String accessTokenKey = RedisPrefixUtils.generateAccessTokenKey(phone, identity);
        String refreshTokenKey = RedisPrefixUtils.generateRefreshTokenKey(phone, identity);

        String accessToken = JwtUtils.generateAccessToken(phone, identity);
        String refreshToken = JwtUtils.generateRefreshToken(phone, identity);

        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 30, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 31, TimeUnit.DAYS);
        return ResponseResult.success(new TokenResponse(accessToken, refreshToken));
    }
}
